﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

namespace CassiniStarter
{
	public partial class Form1 : Form
	{
		private Random rnd = new Random();

		public Form1()
		{
			InitializeComponent();
		}

		private void browseBTN_Click(object sender, EventArgs e)
		{
			showBrowseFolderDialog();
		}

		private void showBrowseFolderDialog()
		{
			folderBrowserDialog1.Description = "Select the root folder for the web application.";
			folderBrowserDialog1.ShowNewFolderButton = false;
			folderBrowserDialog1.SelectedPath = @"C:\Projects\VS2008\";
			if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
			{
				folderTB.Text = folderBrowserDialog1.SelectedPath;
				setRandomPort();
				startBTN.Enabled = true;
				this.Activate();
			}
		}

		private void rndBTN_Click(object sender, EventArgs e)
		{
			setRandomPort();
		}

		private void setRandomPort()
		{
			portTB.Text = rnd.Next(65000, 66001).ToString();
		}

		private void startBTN_Click(object sender, EventArgs e)
		{
			Thread t = new Thread(new ThreadStart(startCassini));
			t.Start();
		}

		private void startCassini()
		{
			Process cassini = new Process();
			cassini.StartInfo.FileName = findCassiniExe();
			string rootFolder = folderTB.Text;
			cassini.StartInfo.Arguments = string.Format("/path:\"{0}\" /port:{1} /vpath:\"{2}\"", folderTB.Text, portTB.Text, virtualPathTB.Text);

			try
			{
				cassini.Start();
			}
			catch (Exception e)
			{
				MessageBox.Show(string.Format("Could not start Cassini with the following arguments:{0}\r\nError:{1}", cassini.StartInfo.Arguments, e),
					"Could not load Cassini.");

				return;
			}

			if (loadPageTB.Checked)
			{
				Thread.Sleep(1000);
				string proc = string.Format("http://localhost:{0}{1}", portTB.Text, virtualPathTB.Text);
				try
				{
					Process.Start(proc);
				}
				catch (Exception e)
				{
					MessageBox.Show(string.Format("Could not load page at '{0}'.  Problem starting Cassini?\r\nError:{1}", proc, e));
					return;
				}
			}

			if (closeAfterLoadCB.Checked)
			{
				Thread.Sleep(1000);

				this.Invoke(
					(MethodInvoker)delegate { this.Close(); }
				);
			}
		}

		private string findCassiniExe()
		{
			string filepath = string.Format(@"C:\Program Files\Common Files\Microsoft Shared\DevServer\9.0\WebDev.WebServer.EXE");
			if (! System.IO.File.Exists(filepath))
			{
				throw new ApplicationException(string.Format("Error.  Could not find Cassini executable in expected location ({0}).  Exiting.", filepath));
			}

			return filepath;
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			showBrowseFolderDialog();
		}
	}
}
